let fs = require('fs')
let sd = require('silly-datetime')
let path = require('path')
var connection = require('../modules/connect')
const {
    isArray
} = require('util')

exports.find = (callback) => {
    connection.query('select * from `historys`', function (err, data) {
        if (err) {
            return callback(err)
        }
        return callback(null, data)
    })
}

exports.save = function (student, callback) {
    if (!student.name) {
        return callback(null, 1)
    } else if (!student.hobbies) {
        return callback(null, 2)
    } else if (!student.age) {
        return callback(null, 3)
    } else if (isNaN(student.gender)) {
        return callback(null, 4)
    } else if (student.name.length < 2 || student.name.length > 10) {
        return callback(null, 5)
    } else if (isNaN(student.age)) {
        return callback(null, 6)
    } else if (parseInt(student.age) <= 0 || parseInt(student.age) >= 150 || student.age == '') {
        return callback(null, 7)
    } else if (student.hobbies.length < 4 || student.hobbies.length > 100) {
        return callback(null, 8)
    } else {
        time = sd.format(new Date(), 'YYYY-MM-DD HH:mm')
        connection.query("insert into `historys` values(null,'" + student.name + "'," + student.gender + "," + student.age + ",'" + student.hobbies + "','" + time + "');", function (err) {
            if (err) {
                return callback(err)
            }
            return callback(null, 0)
        })
    }
}


exports.deleteById = function (ids, callback) {
    if (isArray(ids) === true) {
        var sql = `delete from historys where id in (`; //用来拼接？
        param = [];
        for (let i = 0; i < ids.length; i++) { //循环传过来的id数组，插入到param变量数组中
            param.push(ids[i])
        }
        for (let i = 0; i < ids.length - 1; i++) { //循环拼接sql
            sql = sql + ids[i] + `,`;
        }
        sql = sql + ids[ids.length - 1] + `)`;
        connection.query(sql, function (err) {
            if (err) {
                return callback(err)
            }
            return callback(null)
        })
    } else {
        connection.query(`delete from historys where id=${ids}`, function (err) {
            if (err) {
                return callback(err)
            }
            return callback(null)
        })
    }
}